﻿using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.OleDb;
using System.Collections;
using System.Globalization;

namespace VSM.Parts
{
    public partial class GoodsReceipt : System.Web.UI.Page
    {
        #region Fields
        private string TblHeaderName = "OIGN";
        private string TblLineName = "IGN1";
        private string CurrentPageUrl = "/Business/Parts/Inventory/GoodsReceipt.aspx";
        private string HeaderKeyName = "DocEntry";
        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (Session[Utils.AppConstants.ID_User] == null
                    || Session[Utils.AppConstants.Password] == null
                    || Session[Utils.AppConstants.ID_Dealer] == null)
                {
                    Response.Redirect("../../../Login.aspx");
                }
                if (!IsPostBack)
                {
                    string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                  GeneralFunctions  GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
                    ClearScreen();

                    String grptId = Request.QueryString["grpt_id"];
                    if (!String.IsNullOrEmpty(grptId))
                    {
                        LoadData(grptId, ConvertDocType.Get2String(DocType.GOODS_RECEIPT));
                        SetScreenStatus("Update");
                    }
                    else
                    {
                        LoadDefault();
                        SetScreenStatus("New");
                    }
                }
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvSearchResult_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.grvGRPT.PageIndex = e.NewPageIndex;
            DataTable tblIGN1 = (DataTable)Session["IGN1Table"];
            BindData(tblIGN1);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lnkDelete_Click(object sender, EventArgs e)
        {
            try
            {
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((LinkButton)sender).Parent).Parent;
                Label lblNo = (Label)row.FindControl("lblNo");
                DataTable tblIGN1 = (DataTable)Session["IGN1Table"];
                if (tblIGN1 != null)
                {
                    DataRow[] rupdate = tblIGN1.Select("No=" + lblNo.Text );
                    if (rupdate.Length > 0)
                    {
                        Dictionary<string, string> dicItem = (Dictionary<string, string>)Session["ChosenItem"];
                        if (dicItem != null)
                        {
                            if (dicItem.ContainsKey(rupdate[0]["ItemCode"].ToString()))
                            {
                                dicItem.Remove(rupdate[0]["ItemCode"].ToString());
                            }
                        }
                        tblIGN1.Rows.Remove(rupdate[0]);
                    }
                    this.grvGRPT.EditIndex = -1;
                    BindData((DataTable)Session["IGN1Table"]);
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvSearchResult_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event)");
                e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)");
                e.Row.Attributes["style"] = "cursor:pointer";
                // Load Model
                DropDownList ddlModel = (DropDownList)e.Row.FindControl("ddlModel");
                Label lblModel = (Label)e.Row.FindControl("lblModel");
                if (ddlModel != null)
                {
                    ddlModel.DataSource = GF.GetModelList(dbType);
                    ddlModel.DataValueField = "Code";
                    ddlModel.DataTextField = "Name";
                    ddlModel.DataBind();
                    ddlModel.Items.Insert(0, "");
                    if (lblModel != null) ddlModel.SelectedValue = lblModel.Text;
                }
                // Load Product
                DropDownList ddlProduct = (DropDownList)e.Row.FindControl("ddlProduct");
                if (ddlProduct != null)
                {
                    ddlProduct.DataSource = GF.GetProductByModel(dbType, lblModel.Text);
                    ddlProduct.DataValueField = "Code";
                    ddlProduct.DataTextField = "Name";
                    ddlProduct.DataBind();
                    ddlProduct.Items.Insert(0, "");
                    Label lblProduct = (Label)e.Row.FindControl("lblProduct");
                    if (lblProduct != null) ddlProduct.SelectedValue = lblProduct.Text;
                }
                // Load Color
                DropDownList ddlColor = (DropDownList)e.Row.FindControl("ddlColor");
                if (ddlColor != null)
                {
                    ddlColor.DataSource = GF.GetColorList(dbType);
                    ddlColor.DataValueField = "Code";
                    ddlColor.DataTextField = "Name";
                    ddlColor.DataBind();
                    ddlColor.Items.Insert(0, "");
                    Label lblColor = (Label)e.Row.FindControl("lblColor");
                    if (lblColor != null) ddlColor.SelectedValue = lblColor.Text;
                }

            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtOrderQuantity_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtQuantity = (TextBox)row.FindControl("txtOrderQuantity");
                if (txtQuantity.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input quantity');", true);
                    txtQuantity.Focus();
                    return;
                }
                Label lblNo = (Label)row.FindControl("lblNo");

                DataTable tbIGN1 = (DataTable)Session["IGN1Table"];
                if (tbIGN1 != null)
                {
                    DataRow[] rupdate = tbIGN1.Select("No=" + lblNo.Text);
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["Quantity"] = GF.FormatNumeric(txtQuantity.Text, "QtyDec");
                    }
                }

                this.grvGRPT.EditIndex = -1;

                BindData(tbIGN1);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void EditItem(object sender, GridViewEditEventArgs e)
        {
            this.grvGRPT.EditIndex = e.NewEditIndex;
            BindData((DataTable)Session["IGN1Table"]);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
        {
            e.Cancel = true;
            this.grvGRPT.EditIndex = -1;
            BindData((DataTable)Session["IGN1Table"]);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void DeleteItem(object sender, GridViewDeleteEventArgs e)
        {
            try
            {
                e.Cancel = true;
                GridViewRow row = (GridViewRow)this.grvGRPT.Rows[e.RowIndex];
                Label lblNo = (Label)row.FindControl("lblNo");
                DataTable tbIGN1 = (DataTable)Session["IGN1Table"];
                if (tbIGN1 != null)
                {
                    DataRow[] rupdate = tbIGN1.Select("No=" + lblNo.Text);
                    if (rupdate.Length > 0)
                    {
                        Dictionary<string, string> dicItem = (Dictionary<string, string>)Session["ChosenItem"];
                        if (dicItem != null)
                            if (dicItem.ContainsKey(rupdate[0]["ItemCode"].ToString())) dicItem.Remove(rupdate[0]["ItemCode"].ToString());
                        tbIGN1.Rows.Remove(rupdate[0]);
                    }
                    this.grvGRPT.EditIndex = -1;
                    BindData((DataTable)Session["IGN1Table"]);
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void UpdateItem(object sender, GridViewUpdateEventArgs e)
        {
            try
            {
                ViewState["rowindex"] = e.RowIndex;
                GridViewRow row = (GridViewRow)this.grvGRPT.Rows[e.RowIndex];
                TextBox txtQuantity = (TextBox)row.FindControl("txtOrderQuantity");
                if (txtQuantity.Text.Trim().Length == 0 || int.Parse(txtQuantity.Text.Trim()) == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('In Quantity column, enter whole number greater than 0');", true);
                    txtQuantity.Focus();
                    return;
                }
                Label lblNo = (Label)row.FindControl("lblNo");

                DataTable tb = (DataTable)Session["IGN1Table"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("No=" + lblNo.Text );
                    if (rupdate.Length > 0) rupdate[0]["Quantity"] = txtQuantity.Text;
                    this.grvGRPT.EditIndex = -1;
                    BindData(tb);
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        private void BindData(DataTable tblData)
        {
            Session["IGN1Table"] = tblData;
            this.grvGRPT.DataSource = tblData;
            this.grvGRPT.DataBind();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoadComplete(EventArgs e)
        {
            try
            {
                base.OnLoadComplete(e);
                if (this.Request["__EVENTARGUMENT"] != null && this.Request["__EVENTARGUMENT"].ToString() != "")
                {
                    DataTable tblIGN1 = (DataTable)Session["IGN1Table"];
                    string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;

                    switch (this.Request["__EVENTARGUMENT"].ToString())
                    {
                        case "SelectItem":
                            this.lblError.Visible = false;
                            if (tblIGN1 != null)
                            {
                                Dictionary<string, string> dicItem = Session["ChosenItem"] != null ? (Dictionary<string, string>)Session["ChosenItem"] : null;
                                if (dicItem != null)
                                {
                                    GetDefault defaultWS = new GetDefault();
                                    foreach (KeyValuePair<string, string> item in dicItem)
                                    {
                                        DataSet defaultInfo = defaultWS.GetPartsDefaultLineInfo(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(),
                                             Session[Utils.AppConstants.ID_Dealer].ToString(), item.Key, 1, DateTime.Now.Date, Utils.AppConstants.PARTS,"4");

                                        DataRow rowNew = tblIGN1.NewRow();
                                        rowNew["No"] = (tblIGN1.Rows.Count + 1).ToString();
                                        rowNew["ItemCode"] = item.Key;
                                        rowNew["Dscription"] = item.Value;
                                        if(defaultInfo!=null && defaultInfo.Tables.Count>0 && defaultInfo.Tables[0].Rows.Count>0)
                                        {
                                            rowNew["U_Model"] = defaultInfo.Tables[0].Rows[0]["U_Model"].ToString();
                                            rowNew["unitMsr"] = defaultInfo.Tables[0].Rows[0]["UomCode"].ToString();
                                        }
                                        rowNew["U_Product"] =
                                        rowNew["U_Color"] = string.Empty;
                                        rowNew["Quantity"] = 1;
                                        DataRow[] rExist = tblIGN1.Select("ItemCode='" + item.Key + "'");
                                        if (rExist.Length == 0)
                                        {
                                            tblIGN1.Rows.Add(rowNew);
                                        }
                                    }
                                }
                            }
                            //ReLoad Data
                            BindData(tblIGN1);
                            break;

                        case "SelectDocList":
                            GridViewRow rowDocList = Session["ChosenDocList"] != null ? (GridViewRow)Session["ChosenDocList"] : null;
                            string grptId = ((Label)rowDocList.FindControl("lblDocNum")).Text;
                            string doctype = ((Label)rowDocList.FindControl("lblDocType")).Text;
                            LoadData(grptId, doctype);
                            break;

                        default:
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvGRPO_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                GridViewRow myRow = e.Row;
                Label lblNo = myRow.FindControl("lblNo") as Label;
                lblNo.Text = (myRow.RowIndex + 1).ToString();

                if (this.hdnStatus.Value.Equals("C") )
                {
                    TextBox txtQuantity = (TextBox)myRow.FindControl("txtOrderQuantity");
                    LinkButton lnkDelete = (LinkButton)myRow.FindControl("lnkDelete");
                    if (lnkDelete != null) lnkDelete.Enabled = false;
                    if (txtQuantity != null) lnkDelete.Enabled = false;
                    {
                        txtQuantity.ReadOnly = true;
                        txtQuantity.BackColor = System.Drawing.Color.Transparent;
                        txtQuantity.BorderStyle = BorderStyle.None;
                    }
                }
            }
        }
 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                String requestXML = _collectData();
                if (requestXML == "") return;

                Transaction ts = new Transaction();
                DataSet ds = ts.CreateMarketingDocument(requestXML, ConvertDocType.Get2String(DocType.GOODS_RECEIPT), txtDocNo.Text, hdnIsUpdate.Value.Equals("true"), dbType);
                if ((int)ds.Tables[0].Rows[0]["ErrCode"] != 0)
                {
                    Session["errorMessage"] = ds.Tables[0].Rows[0]["ErrMsg"];
                    Session["requestXML"] = requestXML;
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                        "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ds.Tables[0].Rows[0]["ErrMsg"].ToString()) + "','');", true);
                }
                else
                {
                    Session["successMessage"] = "Operation complete sucessful!";
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + "Operation complete sucessful!" + "','');", true);
                    ClearScreen();
                }
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            CloseCancel(true);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnClose_Click(object sender, EventArgs e)
        {
            CloseCancel(false);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="isClose"></param>
        private void CloseCancel(bool isClose)
        {
            //try
            //{
            //    Transaction obj = new Transaction();
            //    string error = string.Empty;
            //    if (_isPO == "1")
            //    {
            //        //error = obj.CloseCancelPO(int.Parse(_docEntry), _companyCode, isClose, false);
            //    }
            //    else
            //    {
            //        //error = obj.CloseCancelPO(int.Parse(_docEntry), _companyCode, isClose, true);
            //    }
            //    if (error.Length == 0)
            //    {
            //        this.lblError.Text = "Operation complete successful!";
            //        DisableControl();
            //    }
            //    else
            //    {
            //        this.lblError.Text = error;
            //    }
            //}
            //catch (Exception ex)
            //{
            //    this.lblError.Text = ex.Message;
            //}
            //this.lblError.Visible = true;
        }

        private DataTable BuildContents(DataTable dtContent)
        {
            string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
            DataTable dt = new DataTable(TblLineName);
            dt.Columns.Add("No");
            dt.Columns.Add("LineNum");
            dt.Columns.Add("ItemCode");
            dt.Columns.Add("Dscription");
            dt.Columns.Add("U_Model");
            dt.Columns.Add("U_Product");
            dt.Columns.Add("U_Color");
            dt.Columns.Add("Quantity");
            dt.Columns.Add("unitMsr");
            if (dtContent != null)
            {
                foreach (DataRow dr in dtContent.Rows)
                {
                    DataRow row = dt.NewRow();
                    row["No"] = dr["No"];
                    row["LineNum"] = dr["LineNum"];
                    row["ItemCode"] = dr["ItemCode"];
                    row["Dscription"] = dr["Dscription"];
                    row["U_Model"] = dr["U_Model"];
                    row["U_Product"] = dr["U_Product"];
                    row["U_Color"] = dr["U_Color"];
                    row["unitMsr"] = dr["unitMsr"];
                    row["Quantity"] = GF.FormatNumeric(dr["Quantity"].ToString(), "QtyDec");
                    dt.Rows.Add(row);
                }
            }
            return dt;
        }

        protected void LoadDefault()
        {
            this.txtPostingDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
            this.txtDocDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
            this.txtDocNo.Text = string.Empty;

            DataTable dtContents = BuildContents(null);
            BindData(dtContents);
        }

        protected void LoadData(String grptId, string NewDocType)
        {
            string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            Transaction ts = new Transaction();
            DataSet returnDoc = ts.GetMarketingDocument_ReturnDS(NewDocType, grptId, dbType);

            if (returnDoc == null) returnDoc = ts.GetMarketingDocument_ReturnDS(NewDocType, "1", dbType); //grpoId = "1"; get default            

            if (returnDoc == null || returnDoc.Tables.Count < 2)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('No record found!','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                return;
            }

            DataTable dtHeader = returnDoc.Tables[0];
            DataRow dr = dtHeader.Rows[0];
            txtDocNo.Text = dr["DocEntry"].ToString();
            txtPostingDate.Text = String.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(dr["DocDate"], new CultureInfo("es-US")));
            txtDocDate.Text = String.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(dr["TaxDate"], new CultureInfo("es-US")));
            txtRemarks.Text = dr["Comments"].ToString();

            SetScreenStatus("Close");
            DataTable dtContents = BuildContents(returnDoc.Tables[1]);
            BindData(dtContents);
        }

        protected void ClearScreen()
        {
           DataTable dtContents = new DataTable(TblLineName);
            dtContents.Columns.Add("No");
            dtContents.Columns.Add("LineNum");
            dtContents.Columns.Add("ItemCode");
            dtContents.Columns.Add("Dscription");
            dtContents.Columns.Add("U_Model");
            dtContents.Columns.Add("U_Product");
            dtContents.Columns.Add("U_Color");
            dtContents.Columns.Add("unitMsr");
            dtContents.Columns.Add("Quantity");
                        
            CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentCulture;
            txtPostingDate.Text.ToString(ci);
            txtDocDate.Text.ToString(ci); 

            txtDocNo.Text =
            txtRemarks.Text = String.Empty; 

            BindData(dtContents);
            SetScreenStatus("New");
        }

        protected void SetScreenStatus(string Status)
        {
            switch (Status)
            {
                case "New":
                    btnSave.Enabled = true;
                    btnCancel.Enabled = false;
                    hdnIsUpdate.Value = "false";
                    hdnStatus.Value = "O";
                    break;

                case "Update":
                    hdnIsUpdate.Value = "true";
                    btnSave.Enabled = 
                    btnCancel.Enabled = false;
                    hdnStatus.Value = "O";
                    break;

                case "Close":
                    btnSave.Enabled = 
                    btnCancel.Enabled = false;
                    hdnIsUpdate.Value = "false";
                    hdnStatus.Value = "C";
                    break;
            }
        }

        private void BuildSRNT(ref DataTable dtSRNT, string ItemCode, string SysNumber, string DistNumber, string InDate, string Notes,
            double Quantity, string WhsCode, string DocType, string DocEntry, string DocLineNum)
        {
            if (dtSRNT == null)
            {
                dtSRNT = new DataTable("SRNT");
                dtSRNT.Columns.Add("ItemCode");
                dtSRNT.Columns.Add("SysNumber");    // Default
                dtSRNT.Columns.Add("DistNumber");   // VIN Number
                dtSRNT.Columns.Add("InDate");       // Get default
                dtSRNT.Columns.Add("Quantity");     // 1
                dtSRNT.Columns.Add("WhsCode");      // Default
                dtSRNT.Columns.Add("DocType");      // 13
                dtSRNT.Columns.Add("DocEntry");     // Get from Incoming Payment No.
                dtSRNT.Columns.Add("DocLineNum");   // 1
                dtSRNT.Columns.Add("Notes");   // 
                //dtSRNT.Columns.Add("BSubLineNo");   // LineNo
            }

            DataRow drSRNT = dtSRNT.NewRow();
            drSRNT["ItemCode"] = ItemCode;      // INV1
            drSRNT["SysNumber"] = SysNumber;
            drSRNT["DistNumber"] = DistNumber;   // VIN Number
            drSRNT["InDate"] = Utils.AppConstants.ConvertToDate(InDate).ToString("yyyyMMdd");
            drSRNT["Quantity"] = Quantity;       // INV1
            drSRNT["WhsCode"] = WhsCode;         // INV1
            drSRNT["DocType"] = DocType;         // INV1
            drSRNT["DocEntry"] = DocEntry;       // INV1
            drSRNT["DocLineNum"] = DocLineNum;   // INV1
            drSRNT["Notes"] = Notes;
            //drSRNT["BSubLineNo"] = BSubLineNo; // INV1
            dtSRNT.Rows.Add(drSRNT);
        }

        public String _collectData()
        {
            try
            {
                DataSet ds = new DataSet("DS");
                DataTable dtContents = (DataTable)Session["IGN1Table"];
                DataTable dtHeader = new DataTable(TblHeaderName);

                dtHeader.Columns.Add("DocEntry");
                dtHeader.Columns.Add("DocNum");
                dtHeader.Columns.Add("Series");
                dtHeader.Columns.Add("DocStatus");
                dtHeader.Columns.Add("DocDate");
                dtHeader.Columns.Add("TaxDate");
                dtHeader.Columns.Add("Comments");
                // UDF
                dtHeader.Columns.Add("U_DealerID");
                dtHeader.Columns.Add("U_Department");

                DataRow drHeader = dtHeader.NewRow();
                // Add new
                drHeader["Series"] = 19;
                drHeader["DocStatus"] = "O";
                drHeader["DocDate"] = Utils.AppConstants.ConvertToDate(txtPostingDate.Text).ToString("yyyyMMdd");
                drHeader["TaxDate"] = Utils.AppConstants.ConvertToDate(txtDocDate.Text).ToString("yyyyMMdd");
                drHeader["Comments"] = txtRemarks.Text.Trim();
                // UDF
                drHeader["U_DealerID"] = Session[Utils.AppConstants.ID_Dealer].ToString();
                drHeader["U_Department"] = Utils.AppConstants.PARTS;

                dtHeader.Rows.Add(drHeader);
                dtHeader.TableName = TblHeaderName;
                ds.Tables.Add(dtHeader.Copy());

                DataTable dt = new DataTable(TblLineName);
                dt.Columns.Add("DocEntry");
                dt.Columns.Add("LineNum");
                dt.Columns.Add("LineStatus");
                dt.Columns.Add("ItemCode");
                dt.Columns.Add("Dscription");
                dt.Columns.Add("AcctCode");
                dt.Columns.Add("U_Model");
                dt.Columns.Add("U_Product");
                dt.Columns.Add("U_Color");
                dt.Columns.Add("unitMsr");
                dt.Columns.Add("Quantity");
                if (dtContents != null)
                {
                    int liNo = 0;
                    foreach (DataRow dr in dtContents.Rows)
                    {
                        DataRow row = dt.NewRow();
                        row["LineNum"] = liNo;
                        row["LineStatus"] = "O";
                        row["ItemCode"] = dr["ItemCode"];
                        row["Dscription"] = dr["Dscription"];
                        row["AcctCode"] = "999999";
                        row["U_Model"] = dr["U_Model"];
                        row["U_Product"] = dr["U_Product"];
                        row["U_Color"] = dr["U_Color"];
                        row["unitMsr"] = dr["unitMsr"];
                        row["Quantity"] = dr["Quantity"];
                        
                        dt.Rows.Add(row);
                        liNo++;
                    }
                }
                ds.Tables.Add(dt.Copy());

                // Build VIN Number (Serial Number) datatable to save
                DataTable dtSRNT = (DataTable)Session["tblSRNT"];
                if (dtSRNT != null)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        DataRow[] rDocLineNum = dtSRNT.Select("ItemCode='" + dr["ItemCode"].ToString() + "'");
                        if (rDocLineNum.Length > 0)
                        {
                            for (int i = 0; i < rDocLineNum.Length; i++)
                                rDocLineNum[i]["DocLineNum"] = dr["LineNum"];
                        }
                    }
                    if (dtSRNT != null) ds.Tables.Add(dtSRNT.Copy());
                }

                DocumentXML objInfo = new DocumentXML();
                return objInfo.ToXMLStringFromDS( ConvertDocType.Get2String(DocType.GOODS_RECEIPT), ds);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                return string.Empty;
            }
        }

        protected void btnLastRecord_Click(object sender, EventArgs e)
        {
            GetDefault fGetDefault = new GetDefault();
            string lsGRPONo = fGetDefault.GetMaxDocEntry
            (
                Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER, // dbType
                Session[Utils.AppConstants.ID_Dealer].ToString(), 
                Utils.AppConstants.PARTS,
                ConvertDocType.Get2String(DocType.GOODS_RECEIPT), 
                TblHeaderName, HeaderKeyName
            );
            if (txtDocNo.Text.CompareTo(lsGRPONo) != 0)
                Response.Redirect(CurrentPageUrl + "?grpt_id=" + lsGRPONo);
        }

        protected void ddlModel_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((DropDownList)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                DropDownList ddlModel = (DropDownList)row.FindControl("ddlModel");
                if (ddlModel.SelectedValue.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls selection a Model');", true);
                    ddlModel.Focus();
                    return;
                }
                Label lblModel = (Label)row.FindControl("lblModel");
                lblModel.Text = ddlModel.SelectedValue;

                // Load Product
                DropDownList ddlProduct = (DropDownList)row.FindControl("ddlProduct");
                if (ddlProduct != null)
                {
                    string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                    GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
                    ddlProduct.DataSource = GF.GetProductByModel(dbType, ddlModel.SelectedValue);
                    ddlProduct.DataValueField = "Code";
                    ddlProduct.DataTextField = "Name";
                    ddlProduct.DataBind();
                    ddlProduct.Items.Insert(0, "");

                    Label lblProduct = (Label)row.FindControl("lblProduct");
                    lblProduct.Text = ddlProduct.SelectedValue;
                    SetItem(row);
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void ddlProduct_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((DropDownList)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                DropDownList ddlProduct = (DropDownList)row.FindControl("ddlProduct");
                if (ddlProduct.SelectedValue.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls selection a Product');", true);
                    ddlProduct.Focus();
                    return;
                }

                Label lblProduct = (Label)row.FindControl("lblProduct");
                lblProduct.Text = ddlProduct.SelectedValue;
                SetItem(row);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void ddlColor_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((DropDownList)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                DropDownList ddlColor = (DropDownList)row.FindControl("ddlColor");
                if (ddlColor.SelectedValue.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls selection a Color');", true);
                    ddlColor.Focus();
                    return;
                }

                Label lblColor = (Label)row.FindControl("lblColor");
                lblColor.Text = ddlColor.SelectedValue;
                SetItem(row);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        private void SetItem(GridViewRow row)
        {
            string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
            DataTable tblIGN1 = (DataTable)Session["IGN1Table"];
            Label lblNo = (Label)row.FindControl("lblNo");
            DropDownList ddlModel = (DropDownList)row.FindControl("ddlModel");
            DropDownList ddlProduct = (DropDownList)row.FindControl("ddlProduct");
            DropDownList ddlCorlor = (DropDownList)row.FindControl("ddlColor");

            if (ddlModel != null && ddlProduct != null && ddlCorlor != null)
            {
                DataTable dtItem = GF.GetItem(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), ddlModel.SelectedValue, ddlProduct.SelectedValue, ddlCorlor.SelectedValue);
                GetDefault defaultWS = new GetDefault();
                DataRow[] rowUpdate = null;
                if (dtItem != null && dtItem.Rows.Count == 1)
                {
                    rowUpdate = tblIGN1.Select("No=" + lblNo.Text);
                    if (rowUpdate.Length == 1)
                    {
                        rowUpdate[0]["ItemCode"] = dtItem.Rows[0]["ItemCode"].ToString();
                        rowUpdate[0]["Dscription"] = dtItem.Rows[0]["ItemName"].ToString();
                        rowUpdate[0]["U_Model"] = ddlModel.SelectedValue;
                        rowUpdate[0]["U_Product"] = ddlProduct.SelectedValue;
                        rowUpdate[0]["U_Color"] = ddlCorlor.SelectedValue;
                        rowUpdate[0]["Quantity"] = 1;
                    }
                }
                else
                {
                    rowUpdate = tblIGN1.Select("No=" + lblNo.Text);
                    rowUpdate[0]["ItemCode"] =
                    rowUpdate[0]["Dscription"] = string.Empty;
                    rowUpdate[0]["U_Model"] = ddlModel.SelectedValue;
                    rowUpdate[0]["U_Product"] = ddlProduct.SelectedValue;
                    rowUpdate[0]["U_Color"] = ddlCorlor.SelectedValue;
                    rowUpdate[0]["Quantity"] = 1;
                }
                BindData(tblIGN1);
            }
        }

        private DataTable datatable4Exp()
        {
            string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
            DataTable tblPDN1 = (DataTable)Session["IGN1Table"];

            DataTable dtRecords = new DataTable();
            dtRecords.Columns.Add(new DataColumn("Model"));
            dtRecords.Columns.Add(new DataColumn("Product"));
            dtRecords.Columns.Add(new DataColumn("Color"));
            dtRecords.Columns.Add(new DataColumn("Item"));
            dtRecords.Columns.Add(new DataColumn("VIN Number"));
            dtRecords.Columns.Add(new DataColumn("Engin Number"));
            DataRow dr = null;

            foreach (DataRow row in tblPDN1.Rows)
            {
                if (GF.GetItemGroupByCode(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), row["ItemCode"].ToString()).Equals("104")) continue;
                string lsQty = row["Quantity"].ToString();
                int liQty = int.Parse(string.IsNullOrEmpty(lsQty) ? "0" : lsQty.Split('.')[0]);
                if (liQty == 1)
                {
                    dr = dtRecords.NewRow();
                    dr["Model"] = row["U_Model"];
                    dr["Product"] = row["U_Product"];
                    dr["Color"] = row["U_Color"];
                    dr["Item"] = row["ItemCode"];
                    dtRecords.Rows.Add(dr);
                }
                else if(liQty > 1)
                {
                    for (int i = 0; i < liQty; i++)
                    {
                        dr = dtRecords.NewRow();
                        dr["Model"] = row["U_Model"];
                        dr["Product"] = row["U_Product"];
                        dr["Color"] = row["U_Color"];
                        dr["Item"] = row["ItemCode"];
                        dtRecords.Rows.Add(dr);
                    }
                }
            }
            return dtRecords;
        }

        protected void btnAddItems_Click(object sender, EventArgs e)
        {
            DataTable tbIGN1 = (DataTable)Session["IGN1Table"];
            DataRow rowNew = tbIGN1.NewRow();
            rowNew["No"] = (tbIGN1.Rows.Count + 1).ToString();
            rowNew["ItemCode"] =
            rowNew["Dscription"] =
            rowNew["U_Model"] =
            rowNew["U_Product"] =
            rowNew["U_Color"] = string.Empty;
            rowNew["Quantity"] = 1;

            tbIGN1.Rows.Add(rowNew);
            BindData(tbIGN1);
        }

        private bool ImportValidation()
        {

            if (this.FileUploadControl.PostedFile == null && this.FileUploadControl.PostedFile.FileName.Length <= 0)
            {
                Session["errorMessage"] = "Please select a Excel file before click on Import button.";
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + Session["errorMessage"].ToString() + "','');", true);
                return false;
            }
            string lsFileExtension = Path.GetExtension(this.FileUploadControl.PostedFile.FileName);
            if ((!lsFileExtension.Equals(".csv")))
            {
                Session["errorMessage"] = "Invalid file. Please select a .csv file.";
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + Session["errorMessage"].ToString() + "','');", true);
                return false;
            }
            return true;
        }

        protected void btnImport_Click(object sender, EventArgs e)
        {
            if (ImportValidation())
            {
                DataTable dtExcelRecords = new DataTable();
                string fileLocation = Server.MapPath("~/App_Data/");
                if (this.FileUploadControl.HasFile)
                {
                    string fileName = Path.GetFileName(FileUploadControl.PostedFile.FileName);
                    this.FileUploadControl.SaveAs(fileLocation + fileName); // save file to server
                    dtExcelRecords = Utils.AppConstants.ImportCSVFile(fileName, fileLocation);
                }
                DateTime poDate = Utils.AppConstants.ConvertToDate(this.txtPostingDate.Text);
                DataTable tblIGN1 = (DataTable)Session["IGN1Table"];
                string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;

                foreach (DataRow r in dtExcelRecords.Rows)
                {
                    DataRow rowNew = tblIGN1.NewRow();
                    rowNew["No"] = (tblIGN1.Rows.Count + 1).ToString();
                    rowNew["ItemCode"] = r["ItemCode"];
                    rowNew["Dscription"] = r["ItemName"];
                    rowNew["U_Model"] =
                    rowNew["U_Product"] =
                    rowNew["U_Color"] = string.Empty;
                    rowNew["Quantity"] = 1;
                    DataRow[] rExist = tblIGN1.Select("ItemCode='" + r["ItemCode"].ToString() + "'");
                    if (rExist.Length == 0)
                    {
                        tblIGN1.Rows.Add(rowNew);
                    }
                }
                BindData(tblIGN1);

            }
            //if (!ImportValidation()) return;
            //// Reading .csv file
            //string errMsg = GF.ReadFile(this.FileUploadControl.PostedFile.InputStream);
            //if (string.IsNullOrEmpty(errMsg))
            //{
            //    ImportData();
            //}
            //else
            //{
            //    Session["errorMessage"] = errMsg;
            //    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + Session["errorMessage"].ToString() + "','');", true);
            //}
        }

        private void ImportData()
        {
            string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
            DataTable tblSRNT = null;
            for (int x = 1; x < GF.FileLines.Count; x++)
            {
                string[] rowData = GF.FileLines[x].ToString().Split(',');
                BuildSRNT(ref tblSRNT, rowData[3], "", rowData[4], DateTime.Now.ToString("dd/MM/yyyy"), rowData[5], 1, "01", ConvertDocType.Get2String(DocType.GOODS_RECEIPT), "", "");
            }

            Session["tblSRNT"] = tblSRNT;           
        }

        protected void btnGetTemplate_Click(object sender, EventArgs e)
        {
            try
            {
                DataTable dt = datatable4Exp();

                if (dt != null)
                {
                    Response.AddHeader("Content-Disposition", "attachment;filename=GR.csv");
                    Response.ContentType = "text/csv";
                    int iColCount = dt.Columns.Count;

                    for (int i = 0; i < iColCount; i++)
                    {
                        Response.Write("\"" + dt.Columns[i] + "\"");
                        if (i < iColCount - 1)
                        {
                            Response.Write(",");
                        }
                    }

                    Response.Write(Environment.NewLine);
                    // Now write all the rows.
                    for (int x = 0; x < dt.Rows.Count; x++)
                    {
                        for (int i = 0; i < iColCount; i++)
                        {
                            if (!Convert.IsDBNull(dt.Rows[x][i])) Response.Write("\"" + dt.Rows[x][i].ToString() + "\"");
                            if (i < iColCount - 1) Response.Write(",");
                        }
                        Response.Write(Environment.NewLine);
                    }
                    Response.End();
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

    }
}